//
//  StoreManage
//
//  Created by MC on 2017/12/19.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCChooseForPlatformViewController: MCViewController {
    
    private var pageNumber = 1
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking_getStoreBrandList()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func titleButotnClicked() {
        let vc = MCExplainViewController()
        vc.titleStr = "平台选货说明"
        vc.code = "platform_explain_code"
        vc.type = "platform_explain_type"
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func rightItemClicked() {
        
        for model in self.allBrandsArrayM {
            (model as! MCChooseForPlatformScreeningModel).isSelected = false
        }
        screeningView.dataArray = self.allBrandsArrayM

        
        self.view.addSubview(screeningView)
        screeningView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(self.view)
        }
    }
    
    @objc func resetButtonClicked() {
        for model in self.allBrandsArrayM {
            (model as! MCChooseForPlatformScreeningModel).isSelected = false
        }
        screeningView.dataArray = self.allBrandsArrayM
    }
    
    @objc func sureButtonClicked() {
        
        screeningView.removeFromSuperview()
        
        brandIdList.removeAllObjects()
        
        for model in self.allBrandsArrayM {
            if (model as! MCChooseForPlatformScreeningModel).isSelected {
                self.brandIdList.add((model as! MCChooseForPlatformScreeningModel).brandId)
            }
        }
        dataArrayM.removeAllObjects()
        pageNumber = 1
        sendNetworking()
    }
    
    
    @objc func selectedAllButtonClicked() {
        bottomView.selectedAllButton.isSelected = !bottomView.selectedAllButton.isSelected
        for model in dataArrayM {
            (model as! MCChooseForPlatformModel).isSelected = bottomView.selectedAllButton.isSelected
        }
        self.tableView.reloadData()
    }
    
    @objc func batchButtonClicked() {
        let array = NSMutableArray()
        for model in dataArrayM {
            if (model as! MCChooseForPlatformModel).isSelected && (model as! MCChooseForPlatformModel).isOnShelves == 0 {
                array.add((model as! MCChooseForPlatformModel).goodsId)
            }
        }
        if array.count == 0 {
            MCHUD_text(message: "没有可上架的商品", view: self.view, delay: 1.2)
            return
        }
        
        let para = [
            "goodsIdList" : array,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_setGoodsOnShelves, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            MCHUD_text(message: "批量上架成功", view: self.view, delay: 1.2)
            
            self.pageNumber = 1
            self.sendNetworking()
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "pageNum" : pageNumber,
            "brandIdList" : brandIdList
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getBrandGoodsList, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in

            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
            }

            let dataArray = response["data"] as? NSArray ?? []

            if self.dataArrayM.count + dataArray.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                for dict in dataArray {
                    let model = MCChooseForPlatformModel()
                    model.setValuesForKeys(dict as? [String:Any] ?? [:])
                    self.dataArrayM.add(model)
                }
            }
            
            self.tableView.reloadData()

            
        }, dislike: { (response) in }) { (error) in }
    }
    
    func sendNetworking_getStoreBrandList() {
        let para = [ : ] as [String : Any]

        MCNetwork_post(url: JAVA_getStoreBrandList, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in

            let arrayM = NSMutableArray()

            let dataArray = response["data"] as? NSArray ?? []
            for dict in dataArray {
                let model = MCChooseForPlatformScreeningModel()
                model.setValuesForKeys(dict as? [String:Any] ?? [:])
                arrayM.add(model)
            }
            self.allBrandsArrayM = arrayM
            self.screeningView.dataArray = self.allBrandsArrayM

        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.navigationItem.titleView = self.titleButton
        self.view.backgroundColor = UIColor.white
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("筛选", target: self, selector: #selector(rightItemClicked))


        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking()
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking()
        })
    }
    
    func initUI() {
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 50, 0))
        }
        
        view.addSubview(bottomView)
        bottomView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(50)
        }
    }
    
    // MARK: - Setter & Getter
    lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var allBrandsArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var brandIdList: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    
    
    lazy var bottomView: MCChooseForPlatformBottomView = {
        let view = MCChooseForPlatformBottomView()
        view.selectedAllButton.addTarget(self, action: #selector(selectedAllButtonClicked), for: UIControlEvents.touchUpInside)
        view.batchButton.addTarget(self, action: #selector(batchButtonClicked), for: UIControlEvents.touchUpInside)

        return view
    }()
    
    lazy var screeningView: MCChooseForPlatformScreeningView = {
        let view = MCChooseForPlatformScreeningView()
        view.resetButton.addTarget(self, action: #selector(resetButtonClicked), for: UIControlEvents.touchUpInside)
        view.sureButton.addTarget(self, action: #selector(sureButtonClicked), for: UIControlEvents.touchUpInside)

        return view
    }()
    
    
    lazy var titleButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(19)
        button.frame = CGRect.init(x: 0, y: 0, width: 90, height: 30)
        button.setTitleColor(UIColor.black, for: UIControlState.normal)
        button.setTitle("平台选货", for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "Reuse_question"), for: UIControlState.normal)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 78, 0, -78)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15)
        button.addTarget(self, action: #selector(titleButotnClicked), for: UIControlEvents.touchUpInside)
        return button
    }()
}

extension MCChooseForPlatformViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCChooseForPlatformCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.model = self.dataArrayM[indexPath.row] as! MCChooseForPlatformModel
        cell.row = indexPath.row
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.dataArrayM[indexPath.row] as! MCChooseForPlatformModel
        
        
        let vc = MCGoodsDetailViewController()
        vc.goodsId = model.goodsId
        vc.isOnShelves = model.isOnShelves
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}

extension MCChooseForPlatformViewController : MCChooseForPlatformCellDelegate {
    func MCChooseForPlatformCellToShelve(row: Int,button:UIButton) {
        
        MCAlterController_twoOptions(vc: self, message: "是否上架该商品？", confirm: {
            
            let model = self.dataArrayM[row] as! MCChooseForPlatformModel
            let para = [
                "goodsIdList" : [model.goodsId],
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_setGoodsOnShelves, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
                button.isSelected = true
                model.isOnShelves = 1
                
                MCHUD_text(message: "上架成功", view: self.view, delay: 1.2)
                let indexPath = IndexPath.init(row: row, section: 0)
                self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
            }, dislike: { (response) in }) { (error) in }
        }) {
            
        }
    }
}

